using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Linq;

namespace WebBrowser
{
    public class BookmarkManager
    {
        private readonly string _bookmarksFilePath;
        private List<Bookmark> _bookmarks;

        public BookmarkManager()
        {
            var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            var browserDataPath = Path.Combine(appDataPath, "CooBrowser");
            Directory.CreateDirectory(browserDataPath);
            _bookmarksFilePath = Path.Combine(browserDataPath, "bookmarks.json");
            _bookmarks = new List<Bookmark>();
            LoadBookmarks();
        }

        public List<Bookmark> GetBookmarks()
        {
            return _bookmarks.ToList();
        }

        public void AddBookmark(string title, string url, string faviconUrl = "")
        {
            // Check if bookmark already exists
            if (_bookmarks.Any(b => b.Url.Equals(url, StringComparison.OrdinalIgnoreCase)))
            {
                return; // Already bookmarked
            }

            var bookmark = new Bookmark(title, url, faviconUrl);
            _bookmarks.Add(bookmark);
            SaveBookmarks();
        }

        public void RemoveBookmark(string url)
        {
            _bookmarks.RemoveAll(b => b.Url.Equals(url, StringComparison.OrdinalIgnoreCase));
            SaveBookmarks();
        }

        public bool IsBookmarked(string url)
        {
            return _bookmarks.Any(b => b.Url.Equals(url, StringComparison.OrdinalIgnoreCase));
        }

        private void LoadBookmarks()
        {
            try
            {
                if (File.Exists(_bookmarksFilePath))
                {
                    var json = File.ReadAllText(_bookmarksFilePath);
                    _bookmarks = JsonSerializer.Deserialize<List<Bookmark>>(json) ?? new List<Bookmark>();
                }
            }
            catch (Exception)
            {
                _bookmarks = new List<Bookmark>();
            }
        }

        private void SaveBookmarks()
        {
            try
            {
                var json = JsonSerializer.Serialize(_bookmarks, new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(_bookmarksFilePath, json);
            }
            catch (Exception)
            {
                // Handle save error silently
            }
        }
    }
}